Ext.namespace('Divo');
Ext.namespace('Divo.app');

Divo.app.ReadySendList = function() {
  /* ----------------------- private属性 ----------------------- */
  var gridEl = 'ReadyCode-grid';
  var grid, form, selModel, toolbar, win, pModel;
  var data, personId, flag, tofficesId, readySendId;
  var fldCode;
  var win, ids, mGrid, win2, pGrid, detailGrid;
  var button, fldDocName, fldActionRoom, fldNum, fldMSercher, fldToffices;
  var button2, fldMSercher2;
  var d = new Date();
  var year = d.getYear().toString();
  var month = (d.getMonth() + 1).toString();
  var day = d.getDate().toString();
  var time;
  if (month.length > 1) {
    time = year + month;
  } else {
    time = year + "0" + month;
  }

  if (day.length > 1) {
    time = time + day;
  } else {
    time = time + "0" + day;
  }
  /* ----------------------- private方法 ----------------------- */
  // 创建列表
  function createGrid() {
    var queryFlds = new Array();
    var searchFlds = new Ext.util.MixedCollection();
    queryFlds.push('name');
    var fldName = new Ext.form.TextField({
          name : 'name',
          id : gridEl + '-name',
          fieldLabel : '名称',
          allowBlank : true,
          width : 100

        });
    searchFlds.add('name', fldName);

    grid = new Divo.Base.GridView({
          remoteSort : true,
          gridId : gridEl,
          queryFlds : queryFlds,
          searchFlds : searchFlds,
          entityClassName : 'com.our.sys.project1.entity.Person',
          queryUrl : 'person/query',
          jsonId : 'id',
          recordPk : ["id"]
        });
    pGrid = new Divo.Base.GridView({
          remoteSort : true,
          gridId : gridEl + "p",
          entityClassName : 'com.our.sys.project1.entity.ReadySend',
          queryUrl : 'ready_code/query_ready_send',
          jsonId : 'id',
          recordPk : ["id"]
        });
    detailGrid = new Divo.Base.GridView({
          remoteSort : true,
          gridId : gridEl + "detail",
          hasBbar : false,
          entityClassName : 'com.our.sys.project1.entity.ReadyCode',
          queryUrl : 'ready_code/query_by_send',
          jsonId : 'id',
          recordPk : ["id"]
        });
    mGrid = new Divo.Base.GridView({
          remoteSort : true,
          gridId : gridEl + "m",
          queryFlds : queryFlds,
          searchFlds : searchFlds,
          hasBbar : false,
          height : 400,
          checkboxSelectionModel : true,
          autoSelectFirstRow : false,
          entityClassName : 'com.our.sys.project1.entity.ReadyCode',
          queryUrl : 'ready_code/query_ready_goods',
          jsonId : 'id',
          recordPk : ["id"]
        });

    var cm = grid.getColumnModel();
    for (i = 0; i < cm.getColumnCount(); i++) {
      if (cm.getDataIndex(i) == "sex") {
        cm.setRenderer(i, function(val, params, record) {
              if (val == "1") {
                return "男";
              }

              if (val == "2") {
                return "女";
              }
            });
      }

      if (cm.getDataIndex(i) == "type") {
        cm.setRenderer(i, function(val, params, record) {
              if (val == "1") {
                return "医保";
              }

              if (val == "2") {
                return "自费";
              }
            });
      }
    }

    var cm2 = pGrid.getColumnModel();
    for (i = 0; i < cm2.getColumnCount(); i++) {
      if (cm2.getDataIndex(i) == "state") {
        cm2.setRenderer(i, function(val, params, record) {
              if (val == "0") {
                return "正常";
              }

              if (val == "1") {
                return "需要补录";
              }
            });
      }
    }

    var cm3 = detailGrid.getColumnModel();
    for (i = 0; i < cm3.getColumnCount(); i++) {
      if (cm3.getDataIndex(i) == "readyCodeState") {
        cm3.setRenderer(i, function(val, params, record) {
              if (val == "0") {
                return "备码";
              }

              if (val == "1") {
                return "备货";
              }

              if (val == "3") {
                return "配发";
              }

              if (val == "4") {
                return "已划价";
              }

              if (val == "5") {
                return "已入库";
              }
            });
      }

      if (cm3.getDataIndex(i) == "state") {
        cm3.setRenderer(i, function(val, params, record) {
              // TODO
              // 时间有效那么就是有效的
              var endTime = record.data.endTime;
              var year = endTime.substring(0, 4);
              var month = endTime.substring(5, 7);
              var day = endTime.substring(8, 10);
              var endTimeStr = year + month + day;
              if (parseInt(endTimeStr) - parseInt(time) >= 0) {
                return "OK";
              } else {
                return "NO";
              }
            });
      }
    }

    var cm4 = mGrid.getColumnModel();
    for (i = 0; i < cm4.getColumnCount(); i++) {
      if (cm4.getDataIndex(i) == "readyCodeState") {
        cm4.setRenderer(i, function(val, params, record) {
              if (val == "0") {
                return "备码";
              }

              if (val == "1") {
                return "备货";
              }

              if (val == "3") {
                return "配发";
              }

              if (val == "4") {
                return "已划价";
              }

              if (val == "5") {
                return "已入库";
              }
            });
      }

      if (cm4.getDataIndex(i) == "state") {
        cm4.setRenderer(i, function(val, params, record) {
              // TODO
              // 时间有效那么就是有效的
              var endTime = record.data.endTime;
              var year = endTime.substring(0, 4);
              var month = endTime.substring(5, 7);
              var day = endTime.substring(8, 10);
              var endTimeStr = year + month + day;
              if (parseInt(endTimeStr) - parseInt(time) >= 0) {
                return "OK";
              } else {
                return "NO";
              }
            });
      }
    }

    grid.getStore().on('beforeload', function(store, options) {
          store.baseParams.number = fldCode.getValue()
              ? fldCode.getValue()
              : '';
        }, this, true);
    pGrid.getStore().on('beforeload', function(store, options) {
      store.baseParams.name = fldMSercher2.getValue()
          ? fldMSercher2.getValue()
          : '';
      store.baseParams.flag = "1";
    }, this, true);
    detailGrid.getStore().on('beforeload', function(store, options) {
          store.baseParams.readySendId = readySendId;
        }, this, true);
    mGrid.getStore().on('beforeload', function(store, options) {
      store.baseParams.name = fldMSercher.getValue()
          ? fldMSercher.getValue()
          : '';
    }, this, true);
    pModel = pGrid.getSelectionModel();
    pModel.on('rowselect', onPRowSelect);

    selModel = grid.getSelectionModel();
    selModel.on('rowselect', onRowSelect);

    fldCode = new app.base.TextField({
          name : "number",
          dataIndex : "number",
          fieldLabel : "病人住院号",
          width : 150,
          insert_allowed : true,
          update_allowed : true
        });

    fldDocName = new app.base.TextField({
          name : "docName",
          dataIndex : "docName",
          fieldLabel : "手术医师",
          width : 150,
          insert_allowed : true,
          update_allowed : true
        });

    fldActionRoom = new app.base.TextField({
          name : "actionRoom",
          dataIndex : "actionRoom",
          fieldLabel : "手术房间",
          width : 150,
          insert_allowed : true,
          update_allowed : true
        });

    fldNum = new app.base.TextField({
          name : "num",
          dataIndex : "num",
          fieldLabel : "台次",
          width : 150,
          insert_allowed : true,
          update_allowed : true
        });

    fldMSercher = new app.base.TextField({
          name : "sercher",
          dataIndex : "sercher",
          fieldLabel : "查询",
          width : 150,
          insert_allowed : true,
          update_allowed : true
        });
    fldMSercher2 = new app.base.TextField({
          name : "sercher",
          dataIndex : "sercher",
          fieldLabel : "查询",
          width : 150,
          insert_allowed : true,
          update_allowed : true
        });
    button = new Ext.Button({
          id : 'query',
          text : '查询',
          icon : 'resources/img/g_rec_src.png',
          handler : function() {
            mGrid.getStore().load();
          }
        });

    button2 = new Ext.Button({
          id : 'query2',
          text : '查询',
          icon : 'resources/img/g_rec_src.png',
          handler : function() {
            pGrid.getStore().load();
          }
        });

    fldToffices = new app.base.ComboBox({
          id : 'combo-Toffices',
          name : "Toffices",
          dataIndex : "Toffices",
          fieldLabel : '选择科室',
          store : Divo.com.Lib.getTofficesDs(),
          displayField : 'name',
          valueField : 'id',
          forceSelection : true,
          mode : 'remote',
          triggerAction : 'all',
          editable : false,
          selectOnFocus : true,
          width : 150,
          insert_allowed : true,
          update_allowed : true,
          onSelect : function(record) {
            var data = record.data;
            this.setValue(data.name);
            tofficesId = data.id;
            this.onTriggerClick();
          }
        });
  }

  function onRowSelect(selModel, rowIndex, record) {
    var data = record.data;
    personId = data.id;
    flag = "0";
  }

  function onPRowSelect(pModel, rowIndex, record) {
    var data = record.data;
    readySendId = data.id;
    detailGrid.load();
  }

  // 刷新列表
  function reloadRecords() {
    grid.getStore().reload();
  }

  // 创建layout
  function createLayout() {
    toolbar = new Ext.Toolbar({
          items : [fldCode, "-", {
                icon : "resources/img/g_rec_refresh.gif",
                text : "提取",
                id : "tlb_REFRESH",
                handler : reloadRecords
              }, "-", {
                icon : "resources/img/g_rec_new.png",
                text : "配发",
                id : "tlb_SEND",
                handler : send
              }, "-", {
                icon : "resources/img/g_rec_new.png",
                text : "补录",
                id : "tlb_reSend",
                handler : reSend
              }]
        });

    mToolbar1 = new Ext.Toolbar({
          items : ["手术医师：", fldDocName, "-", "手术房间", fldActionRoom, "-", "台次",
              fldNum, "-", "申请科室：", fldToffices]
        });

    mToolbar2 = new Ext.Toolbar({
          items : ["品牌名、耗材名、供应商名称： ", fldMSercher, button]
        });

    pToolbar = new Ext.Toolbar({
          items : ["起始时间：  ", fldMSercher2, "-", button2]
        });
    var viewport = new Ext.Viewport({
          layout : 'border',
          items : [{
                layout : 'border',
                region : 'center',
                border : false,
                items : [{
                      layout : 'fit',
                      region : 'north',
                      border : false,
                      items : [toolbar],
                      height : 25
                    }, {
                      layout : 'fit',
                      region : 'center',
                      border : false,
                      items : [grid]
                    }]
              }]
        });
    viewport.doLayout();

    fldCode.focus();
  }

  function send() {
    var sels = grid.getSelectionModel().getSelections();
    if (sels.length <= 0) {
      flag = "1";
    }
    mGrid.load();
    win = new Ext.Window({
          title : '选择高值耗材',
          iconCls : 'icon-win',
          autoHeight : true,
          width : 850,
          layout : 'form',
          plain : false,
          buttonAlign : 'right',
          closable : false,
          modal : true,
          items : [{
                layout : 'border',
                region : 'north',
                border : false,
                items : [{
                      layout : 'fit',
                      region : 'north',
                      border : false,
                      items : [mToolbar1],
                      height : 25
                    }, {
                      layout : 'fit',
                      region : 'center',
                      border : false,
                      items : [mToolbar2]
                    }],
                height : 50
              }, {
                layout : 'fit',
                region : 'center',
                border : false,
                items : [mGrid]
              }]
        });
    var yesBtn = win.addButton({
          text : '确定'
        }, commitForm, this);
    var cancelBtn = win.addButton({
          text : '关闭'
        }, onWinHide, this);

    win.show();
  }

  function reSend() {
    var sels = grid.getSelectionModel().getSelections();
    if (sels.length <= 0) {
      Ext.Msg.alert('错误', "请选择一个病人！");
      return;
    }
    pGrid.load();
    win2 = new Ext.Window({
          title : '选择已配发记录',
          iconCls : 'icon-win',
          width : 850,
          height : 500,
          layout : 'form',
          plain : false,
          buttonAlign : 'right',
          closable : false,
          modal : true,
          items : [{
                layout : 'fit',
                region : 'north',
                border : false,
                items : [pToolbar],
                height : 25
              }, {
                layout : 'fit',
                region : 'center',
                border : false,
                items : [pGrid],
                height : 200
              }, {
                layout : 'fit',
                region : 'south',
                border : false,
                items : [detailGrid],
                height : 200
              }]
        });
    var yesBtn = win2.addButton({
          text : '确定'
        }, commitForm2, this);
    var cancelBtn = win2.addButton({
          text : '关闭'
        }, onWinHide2, this);

    win2.show();
  }

  function commitForm() {
    var ids;
    var sels = mGrid.getSelectionModel().getSelections();
    for (var i = 0; i < sels.length; i++) {
      var sel = sels[i];
      if (null == ids) {
        ids = sel.id;
      } else {
        ids = ids + "," + sel.id;
      }
    }
    var perSel = grid.getSelectionModel().getSelections();
    var number;
    if (perSel.length > 0) {
      flag = "0";
      var per = perSel[0];
      number = per.data.number;
    } else {
      flag = "1";
    }
    var docName = fldDocName.getValue();
    var actionRoom = fldActionRoom.getValue();
    var num = fldNum.getValue();
    Ext.Ajax.request({
          params : {
            ids : ids,
            docName : docName,
            actionRoom : actionRoom,
            num : num,
            flag : flag,
            tofficesId : tofficesId,
            number : number
          },
          url : "ready_code/ready_send",
          callback : function(o, s, r) {
            var respText = Ext.decode(r.responseText);
            if (respText.success) {
              fldCode.setValue("");
              grid.getStore().removeAll();
              onWinHide();
              Ext.Msg.alert('成功', "配发成功！");
            } else {
              if (respText.message.length > 0)
                Ext.Msg.alert('错误', respText.message);
            }
          }
        });
  }

  function onWinHide() {
    win.hide();
  }
  function commitForm2() {
    var perSel = grid.getSelectionModel().getSelections();
    var number;
    if (perSel.length > 0) {
      var per = perSel[0];
      number = per.data.number;
    }
    Ext.Ajax.request({
          params : {
            number : number,
            rId : readySendId
          },
          url : "ready_code/ready_re_send",
          callback : function(o, s, r) {
            var respText = Ext.decode(r.responseText);
            if (respText.success) {
              onWinHide2();
              grid.getStore().removeAll();
              pGrid.getStore().removeAll();
              detailGrid.getStore().removeAll();
              Ext.Msg.alert('成功', "配发成功！");
            } else {
              if (respText.message.length > 0)
                Ext.Msg.alert('错误', respText.message);
            }
          }
        });
  }
  function onWinHide2() {
    win2.hide();
  }

  /* ----------------------- public方法 ----------------------- */
  return {
    /**
     * 初始化
     */
    init : function() {
      createGrid();
      createLayout();
    }
  }
}();

Ext.onReady(Divo.app.ReadySendList.init, Divo.app.ReadySendList, true);